package com.gosling.cloudspace.tools;

import com.gosling.cloudspace.common.constants.CommonCodeEnum;
import com.gosling.cloudspace.common.entity.BaseResult;

import java.util.concurrent.RecursiveTask;
import java.util.stream.IntStream;

/**
 * 并行工具类
 *
 * @author lihonglin
 * @date 2022/5/24 15:01
 */
public class RecursiveTaskTool extends RecursiveTask<BaseResult> {

    /**
     * 最大计算数
     */
    private static final int MAX_THRESHOLD = 100;
    private final int start;
    private final int end;

    public RecursiveTaskTool(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected BaseResult compute() {
        //判断计算范围，如果小于等于5，那么一个线程计算就够了，否则进行分割
        if ((end - start) <= MAX_THRESHOLD) {
            //返回[start,end]的总和
            int sum = IntStream.rangeClosed(start, end).sum();
            return BaseResult.success(CommonCodeEnum.SUCCESS, sum);
        } else {
            //任务分割
            int middle = (end + start) / 2;
            RecursiveTaskTool task1 = new RecursiveTaskTool(start, middle);
            RecursiveTaskTool task2 = new RecursiveTaskTool(middle + 1, end);
            //执行
            task1.fork();
            task2.fork();
            //等待返回结果
            BaseResult resultTask1 = task1.join();
            BaseResult resultTask2 = task2.join();
            int joinSum = Integer.parseInt(resultTask1.getData().toString()) + Integer.parseInt(resultTask2.getData().toString());
            return BaseResult.success(CommonCodeEnum.SUCCESS, joinSum);
        }
    }
}